/*
 *  Copyright 2008 Danny Lagrouw
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License. 
 */
package org.bastion.init;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.bastion.adapter.Adapter;
import org.bastion.event.Event;
import org.bastion.event.FindEvent;
import org.bastion.event.RegisterEvent;

public class Domain {

    private final static ThreadLocal<Domain> instance = new ThreadLocal<Domain>(); 
    
	@SuppressWarnings("unchecked")
	private HashMap<Class, List<Adapter>> adapters = new HashMap<Class, List<Adapter>>();
    
    private Domain() {
    }
    
    public static Domain getInstance() {
        Domain domain = instance.get();
        if (domain == null) {
        	domain = new Domain();
        	instance.set(domain);
        }
        return domain;
    }
    
    @SuppressWarnings("unchecked")
	public <T extends Event> void registerAdapter(Class<T> eventClass, Adapter<T> adapter) {
    	List<Adapter> eventAdapters = adapters.get(eventClass);
    	if (eventAdapters == null) {
    		eventAdapters = new ArrayList<Adapter>();
    		adapters.put(eventClass, eventAdapters);
    	}
    	eventAdapters.add(adapter);
    }

    public static void register(Object object) {
    	throwEvent(new RegisterEvent(object));
    }
    
    public static <T extends Event> T throwEvent(T event) {
    	return Domain.getInstance().throwEventInternal(event);
    }
    
    @SuppressWarnings("unchecked")
	public <T extends Event> T throwEventInternal(T event) {
        List<Adapter> eventAdapters = adapters.get(event.getClass());
        if (eventAdapters != null) {
        	for (Adapter<? super Event> adapter : eventAdapters) {
				adapter.handle(event);
			}
        }
        return event;
    }
    
    public <T extends Object> T getObject(Class<T> t, Long id) {
        FindEvent<T> event = new FindEvent<T>(t, id);
        throwEventInternal(event);
        return event.getResult();
    }

}
